package com.zhaojk.audio.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhaojk.audio.config.MiniMaxT2AConfig;
import com.zhaojk.audio.domain.T2ARequest;
import com.zhaojk.audio.domain.T2AResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Base64;

/**
 * MINIMAX 大模型语音服务实现
 *
 * @author zhaojk
 */
@Slf4j
@Service
@Primary
public class MiniMaxAudioServiceImpl implements AudioService{
    private final MiniMaxT2AConfig miniMaxConfig;
    private final ObjectMapper objectMapper;

    @Autowired
    public MiniMaxAudioServiceImpl(MiniMaxT2AConfig miniMaxConfig, ObjectMapper objectMapper) {
        this.miniMaxConfig = miniMaxConfig;
        this.objectMapper = objectMapper;
    }

    public T2AResponse textToAudio(T2ARequest request) throws Exception {
        String url = miniMaxConfig.getT2aUrl() + "?GroupId=" + miniMaxConfig.getGroupId();

        // 设置请求头
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Authorization", "Bearer " + miniMaxConfig.getApiKey());
        httpPost.setHeader("Content-Type", "application/json");

        // 设置请求体
        String requestBody = objectMapper.writeValueAsString(request);
        httpPost.setEntity(new StringEntity(requestBody));

        // 发送请求
        try (CloseableHttpClient httpClient = HttpClients.createDefault();
             CloseableHttpResponse response = httpClient.execute(httpPost)) {

            HttpEntity entity = response.getEntity();
            String responseBody = EntityUtils.toString(entity);

            // 解析响应
            T2AResponse t2aResponse = objectMapper.readValue(responseBody, T2AResponse.class);

            // 解码音频数据
            if (t2aResponse.getData() != null && t2aResponse.getData().getAudio() != null) {
                String audioHex = t2aResponse.getData().getAudio();
                byte[] audioBytes = hexStringToByteArray(audioHex);
                String audioBase64 = Base64.getEncoder().encodeToString(audioBytes);
                t2aResponse.getData().setAudio(audioBase64);
            }else{
                //异常情况处理
                if(t2aResponse.getBaseResp() != null){
                    throw new Exception(t2aResponse.getBaseResp().getStatusMsg());
                }
            }

            return t2aResponse;
        }
    }

    private byte[] hexStringToByteArray(String s) {
        int len = s.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                    + Character.digit(s.charAt(i+1), 16));
        }
        return data;
    }

    @Override
    public byte[] generateAudioFromText(String text) {
        return new byte[0];
    }

    @Override
    public String generateAudioFileFromText(String text) throws Exception {
        return null;
    }

    @Override
    public String generateAudioBase64FromText(String text, int repeat, boolean isRandom) throws Exception {
        T2ARequest request = new T2ARequest();
        request.setModel("speech-02-hd");
        request.setText(text);
        request.setStream(false);

        T2ARequest.VoiceSetting voiceSetting = new T2ARequest.VoiceSetting();
        voiceSetting.setVoiceId("English_CalmWoman");
        voiceSetting.setSpeed(1);
        voiceSetting.setVol(1);
        voiceSetting.setPitch(0);
        voiceSetting.setEmotion("happy");
        request.setVoiceSetting(voiceSetting);

        // 如果需要发音字典
        // Map<String, List<String>> pronunciationDict = new HashMap<>();
        // pronunciationDict.put("tone", Arrays.asList("处理/(chu3)(li3)", "危险/dangerous"));
        // request.setPronunciationDict(pronunciationDict);

        T2ARequest.AudioSetting audioSetting = new T2ARequest.AudioSetting();
        audioSetting.setSampleRate(32000);
        audioSetting.setBitrate(128000);
        audioSetting.setFormat("mp3");
        audioSetting.setChannel(1);
        request.setAudioSetting(audioSetting);

        T2AResponse response = textToAudio(request);
        log.info("Response: " + response);
        String base64Encoded = response.getData().getAudio();
        // 解码Base64数据为字节数据
        byte[] audioBytes = Base64.getDecoder().decode(base64Encoded);
        // 重复音频数据三次
        byte[] repeatedAudioBytes = new byte[audioBytes.length * repeat];
        for (int i = 0; i < repeat; i++) {
            System.arraycopy(audioBytes, 0, repeatedAudioBytes, i * audioBytes.length, audioBytes.length);
        }
        // 将重复后的音频数据重新编码为Base64
        String repeatedBase64Encoded = Base64.getEncoder().encodeToString(repeatedAudioBytes);
        return repeatedBase64Encoded;
    }
}
